package com.huihuiyun.huihuiyun.server.controller.manager.website;

import com.huihuiyun.huihuiyun.server.controller.manager.website.authorize.ManagerWebsiteAuthorizeHandler;
import com.huihuiyun.huihuiyun.server.controller.manager.website.viewobjects.User;
import com.huihuiyun.huihuiyun.server.domain.HhyManager;
import com.huihuiyun.huihuiyun.server.service.HhyManagerService;
import com.huihuiyun.huihuiyun.server.service.MockRedisService;
import com.mark.util.CommonUtil;
import com.mark.util.CookieUtil;
import com.mark.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.PassiveExpiringMap;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

@Path(Const.context)
@Component
@Slf4j
public class ManagerWebsiteController {

    @Autowired
    private ManagerWebsiteAuthorizeHandler managerWebsiteAuthorizeHandler;

    @Context
    private HttpServletRequest httpServletRequest;

    @Context
    private HttpServletResponse httpServletResponse;

    @Autowired
    private MockRedisService mockRedisService;

    @Autowired
    private HhyManagerService hhyManagerService;

    private PassiveExpiringMap<String, String> loginUserMap = new PassiveExpiringMap(30 * 60 * 1000); // Expiration time of 1 sec

    //    {"name":"Serati Ma","avatar":"https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png","userid":"00000001","notifyCount":12}
    @GET
    @Path("/currentUser")
    @Produces(MediaType.APPLICATION_JSON)
    public Response currentUser() {
        try {
            HhyManager hhyManager = managerWebsiteAuthorizeHandler.getHhyManager(httpServletRequest);
            if (hhyManager == null) {
                return managerWebsiteAuthorizeHandler.createNoAuthorizedResponse();
            }
            User user = new User();
            user.name = hhyManager.name;
            user.avatar = "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png";
            user.userid = hhyManager.id;
            user.notifyCount = 12;
            return Response.ok(user).build();
        } catch (Exception e) {
            log.error("", e);
            return Response.serverError().build();
        }
    }

    /**
     * 输入
     * <code>
     * {
     * "credentials":"include","method":"POST",
     * "body":" {\"userName\":\"admin\",\"password\":\"888888\",\"remember\":true,\"type\":\"account\"}",
     * "headers":{"Accept":"application/json","Content-Type":"application/json; charset=utf-8"}
     * }
     * </code>
     * 输出
     * <code>
     * {"status":"ok","type":"account"}
     * </code>
     */
    @POST
    @Path("/login/account")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response loginAccount(Map<String, String> data) {
        try {
            log.error("loginAccount, data=" + JsonUtil.bean2Json(data));

            String type = data.get("type");

            // 用户密码登录
            if ("account".equals(type)) {
                String name = data.get("userName");
                String password = data.get("password");
                HhyManager hhyManager = hhyManagerService.findHhyManagerByLoginNameAndPassword(name, password);
                if (hhyManager != null) {
                    managerWebsiteAuthorizeHandler.afterLoginSuccess(httpServletResponse, hhyManager);
                    Map map = new HashMap();
                    map.put("status", "ok");
                    map.put("type", type);
                    map.put("currentAuthority", "admin");
                    return Response.ok(map).build();
                } else {
                    Map map = new HashMap();
                    map.put("status", "error");
                    map.put("message", "用户/密码错误。。。。");
                    map.put("type", type);
                    map.put("currentAuthority", "admin");
                    return Response.ok(map).build();
                }
            }
            // 手机密码登录
            if ("mobile".equals(type)) {
                String name = data.get("phone");
                String password = data.get("password");
                HhyManager hhyManager = hhyManagerService.findHhyManagerByPhoneAndPassword(name, password);
                if (hhyManager != null) {
                    managerWebsiteAuthorizeHandler.afterLoginSuccess(httpServletResponse, hhyManager);
                    Map map = new HashMap();
                    map.put("status", "ok");
                    map.put("type", type);
                    map.put("currentAuthority", "admin");
                    return Response.ok(map).build();
                } else {
                    Map map = new HashMap();
                    map.put("status", "error");
                    map.put("message", "手机/密码错误。。。。");
                    map.put("type", type);
                    map.put("currentAuthority", "admin");
                    return Response.ok(map).build();
                }
            }
            Map map = new HashMap();
            map.put("status", "error");
            map.put("message", "用户密码错误。。。。");
            map.put("type", type);
            map.put("currentAuthority", "admin");
            return Response.ok().build();
        } catch (Exception e) {
            log.error("", e);
            return Response.serverError().build();
        }
    }

    @POST
    @Path("/logout/account")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response logoutAccount() {
        try {
            String token = CookieUtil.get(httpServletRequest, "token");
            if (token != null) {
                mockRedisService.delete(token);
            }
            CookieUtil.set(httpServletResponse, "token", null, 0);

            return Response.ok().build();
        } catch (Exception e) {
            log.error("", e);
            return Response.serverError().build();
        }
    }

    @POST
    @Path("/forms")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Map forms(Map map) {
        Map result = new HashMap<>();
        result.put("message", "OK");
        return result;
    }

    @GET
    @Path("/profile/basic")
    @Produces(MediaType.APPLICATION_JSON)
    public Map profileBasic() {
        Map map = new HashMap();
        map.put("basicGoods", loadListFromResource("basicGoods.json"));
        map.put("basicProgress", loadListFromResource("basicProgress.json"));
        return map;
    }

    @GET
    @Path("/profile/advanced")
    @Produces(MediaType.APPLICATION_JSON)
    public Map profileAdvanced() {
        Map map = new HashMap();
        map.put("advancedOperation1", loadListFromResource("advancedOperation1.json"));
        map.put("advancedOperation2", loadListFromResource("advancedOperation2.json"));
        map.put("advancedOperation3", loadListFromResource("advancedOperation3.json"));
        return map;
    }

    private List loadListFromResource(String resourceName) {
        List list = new Vector();
        try {
            InputStream inputStream = CommonUtil.readResource(resourceName);
            String string = IOUtils.toString(inputStream);
            list = JsonUtil.json2Bean(string, List.class);
        } catch (Exception e) {
            log.error("", e);
        }
        return list;
    }
}
